/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-05-13     lyh       the first version
 * 消息队列示例代码
 * 1.创建/初始化
 * 2.发送
 * 3.接收
 * 4.删除
 */

#include <rtthread.h>
#include <rtdevice.h>

#define THREAD_PRIORITY         25
#define THREAD_STACK_SIZE       512
#define THREAD_TIMESLICE        5

static rt_mq_t mq = RT_NULL;
static rt_thread_t tid1 = RT_NULL;
static rt_thread_t tid2 = RT_NULL;

static void tid1_entry(void * params)
{
    char buf = 0;
    rt_uint8_t cnt = 0;

    while (1)
    {
        /* 从消息队列中接收消息 */
        if (rt_mq_recv(mq, &buf, sizeof(buf), RT_WAITING_FOREVER) == RT_EOK)
        {
            rt_kprintf("thread1: recv msg from msg queue, the content:%c\n", buf);
            if (cnt == 19)
            {
                break;
            }
        }
        /* 延时 50ms */
        cnt++;
        rt_thread_mdelay(50);
    }
    rt_kprintf("thread1: detach mq \n");
    rt_mq_detach(mq);
}

static void tid2_entry(void * params)
{
    int result;
    char buf = 'A';
    rt_uint8_t cnt = 0;

    while (1)
    {
        if (cnt == 8)
        {
            /* 发送紧急消息到消息队列中 */
            result = rt_mq_urgent(mq, &buf, 1);
            if (result != RT_EOK)
            {
                rt_kprintf("rt_mq_urgent ERR\n");
            }
            else
            {
                rt_kprintf("thread2: send urgent message - %c\n", buf);
            }
        }
        else if (cnt >= 20)/* 发送 20 次消息之后退出 */
        {
            rt_kprintf("message queue stop send, thread2 quit\n");
            break;
        }
        else
        {
            /* 发送消息到消息队列中 */
            result = rt_mq_send(mq, &buf, 1);
            if (result != RT_EOK)
            {
                rt_kprintf("rt_mq_send ERR\n");
            }

            rt_kprintf("thread2: send message - %c\n", buf);
        }
        buf++;
        cnt++;
        /* 延时 5ms */
        rt_thread_mdelay(5);
    }

}

int messagequeue_demo(void)
{

    mq = rt_mq_create("mq1", THREAD_STACK_SIZE, 5, RT_IPC_FLAG_FIFO);

    tid1 = rt_thread_create("mq thread 1", tid1_entry, RT_NULL,
    THREAD_STACK_SIZE, THREAD_PRIORITY, THREAD_TIMESLICE);

    tid2 = rt_thread_create("mq thread 2", tid2_entry, RT_NULL,
    THREAD_STACK_SIZE, THREAD_PRIORITY, THREAD_TIMESLICE);

    rt_thread_startup(tid1);
    rt_thread_startup(tid2);
    return 0;
}

MSH_CMD_EXPORT(messagequeue_demo, messagequeue_demo)
